controllers.controller('AveragesGraphCtrl', ['$scope', '$http', '$q', function($scope, $http, $q) {
    $http(jsRoutes.controllers.StationsController.getAllStations()).success(function(data, status, headers, config) {
        //sababa
        $scope.stations = data;
    }).error(function(data, status, headers, config) {
            alert("error fetching stations")
        })

    $scope.submitGraph = function() {
        if($scope.graph.startDate){
            var defer = $q.defer();
            $scope.graphPromise = defer.promise;
            $http.post(jsRoutes.controllers.StationsController.getAvgGraph().url, {startDate: $scope.graph.startDate.toString(),
                endDate: $scope.graph.endDate ? $scope.graph.endDate.toString():$scope.graph.endDate, stations: $scope.graph.stations.join(",")})
                .success(function(data, status, headers, config) {
                    //sababa
                    $scope.graphData = data.map(function(d) {
                        d.value = (d.value / 60)*5;
                        console.log(d.value)
                        return d;
                    });

                    $scope.showGraph($scope.graphData);
                    defer.resolve();
                }).error(function(data, status, headers, config) {
                    alert("error fetching graphData")
                })

        }
    }

    $('.dropdown-toggle').dropdown('toggle');

    var margin = {top: 20, right: 20, bottom: 30, left: 40},
        width = 960 - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;

    var formatPercent = d3.format("r");

    var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], 0.05);

    var y = d3.scale.linear()
        .range([height, 0]);

    var svg = d3.select(".averagesGraph").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    $scope.showGraph = function(data) {
        // removes previous data
        svg.selectAll("g").remove();
        svg.selectAll("rect").remove();

        var xScale = d3.scale.ordinal()
            .domain(d3.range(data.length))
            .rangeRoundBands([0, width], 0.05);

        var yScale = d3.scale.linear()
            .domain([0, d3.max(data, function(d) {return d.value;})])
            .range([0, height]);

        var xAxis = d3.svg.axis()
            .scale(x)
            .orient("bottom");

        var yAxis = d3.svg.axis()
            .scale(y)
            .orient("left")
            .tickFormat(formatPercent);

        x.domain(data.map(function(d) { return d.data.name; }));
        y.domain([0, d3.max(data, function(d) { return d.value; })]);

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis)
            .append("text")
            .attr("transform", "rotate(-90)")
            .attr("y", 6)
            .attr("dy", ".30em")
            .style("text-anchor", "end")
            .text("Minutes");

        //Create bars
        svg.selectAll("rect")
            .data(data, function(d) {
                return d.data.name;
            })
            .enter()
            .append("rect")
            .attr("x", function(d, i) {
                return xScale(i);
            })
            .attr("y", function(d) {
                return height - yScale(d.value);
            })
            .attr("width", xScale.rangeBand())
            .attr("height", function(d) {
                return yScale(d.value);
            })
            .attr("fill", function(d) {
                return "rgb(0, 0, " + (d.value * 88).toFixed() + ")";
            })

            //Tooltip
            .on("mouseover", function(d) {
                //Get this bar's x/y values, then augment for the tooltip
                var xPosition = parseFloat(d3.select(this).attr("x")) + xScale.rangeBand() / 2;
                var yPosition = parseFloat(d3.select(this).attr("y")) + 14;

                //Update Tooltip Position & value
                d3.select("#tooltip")
                    .style("left", xPosition + "px")
                    .style("top", yPosition + "px")
                    .select("#value")
                    .text(d.value);
                d3.select("#tooltip").classed("hidden", false)
            })
            .on("mouseout", function() {
                //Remove the tooltip
                d3.select("#tooltip").classed("hidden", true);
            })
//            .on("click", function(d) {
//                console.log(d);
//                $http.post(jsRoutes.controllers.ObjectsController.getObjectHistory().url, {startDate: $scope.graph.startDate.toString(),
//                    endDate: $scope.graph.endDate ? $scope.graph.endDate.toString():$scope.graph.endDate, stations: d.station.id.toString()})
//                    .success(function(data, status, headers, config) {
//                        //sababa
//                        $scope.tagsData = data;
//                        $('#tagsModal')
//                            .modal({keyboard: false });
//                    }).error(function(data, status, headers, config) {
//                        alert("error fetching graphData")
//                    })
//            });

        d3.select("input[type='checkbox']").on("change", change);

        function change() {
            // Copy-on-write since tweens are evaluated after a delay.
            var x0 = x.domain(data.sort(this.checked
                        ? function(a, b) { return b.value - a.value; }
                        : function(a, b) { return d3.ascending(a.data.name, b.data.name); })
                    .map(function(d) { return d.data.name; }))
                .copy();

            var transition = svg.transition().duration(750),
                delay = function(d, i) { return i * 50; };

            transition.selectAll("rect")
                .delay(delay)
                .attr("x", function(d) { return x0(d.data.name); });

            transition.select(".x.axis")
                .call(xAxis)
                .selectAll("g")
                .delay(delay);
        }
    };
}]);
